﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

using NuMetaheuristics;

namespace NuMetaheuristics.Utility
{
    public class BinarySerializer<T>
    {
        public void Serialize(T item, string path)
        {
            var writer = new FileStream(path, FileMode.Create);
            var serializer = new BinaryFormatter();
            

            using (writer)
            {
                serializer.Serialize(writer, item);
                //try
                //{
                    
                //}
                //catch (Exception e)
                //{
                //    System.Console.WriteLine("Exception caught: " + e);
                //}
                writer.Close();
            }
        }

        public T Deserialize(string path)
        {
            var serializer = new BinaryFormatter();
            var reader = new FileStream(path, FileMode.Open);

            T item = default(T);

            using (reader)
            {
                item = (T) serializer.Deserialize(reader);
                //try
                //{
                //    item = (T)serializer.ReadObject(reader);
                //}
                //catch (Exception e)
                //{
                //    System.Console.WriteLine("Exception caught: " + e);
                //}
                reader.Close();
            }

            return item;
        }
    }
}
